'use strict';

class CountersDao {
    handle: any
    constructor(db) {
        this.handle = db.collection("counters")
    }
    new = async (sequenceName) => {
        let res = await this.findOne({ id: sequenceName })
        if (!res) {
            this.handle.insert({ id: sequenceName, sequence_value: 10000 })
        }
    }

    getNextSequenceValue = async (sequenceName) => {
        var sequenceDocument = await this.handle.findOneAndUpdate(
            { id: sequenceName },
            { $inc: { sequence_value: 1 } }
        );
        return sequenceDocument.value.sequence_value;
    }

    findOne = async (query): Promise<any> => {
        return await this.handle.findOne(query)
    }

    find = async (query): Promise<any[]> => {
        return await this.handle.find(query).toArray()
    }

    findByPage = async (query, start: number, size: number): Promise<any[]> => {
        return await this.handle.find(query).skip(start).limit(size).toArray()
    }

    findByPageAndSort = async (query, sort, start, size): Promise<any[]> => {
        return await this.handle.find(query).sort(sort).skip(start).limit(size).toArray()
    }
    //opts  { multi: true}
    updateMany = async (query, data): Promise<any> => {
        return await this.handle.updateMany(query, data);
    }

    updateOne = async (query, data): Promise<any> => {
        return await this.handle.updateOne(query, data);
    }

    count = async (query): Promise<number> => {
        return await this.handle.countDocuments(query)
    }

    remove = async (query): Promise<any> => {
        return await this.handle.remove(query, {
            multi: true
        });
    }
}

export default CountersDao